package com.vote.web.controller.common;

import com.vote.common.annotation.Anonymous;
import com.vote.common.config.RuoYiConfig;
import com.vote.common.constant.Constants;
import com.vote.common.core.domain.AjaxResult;
import com.vote.common.utils.StringUtils;
import com.vote.common.utils.file.FileUploadUtils;
import com.vote.common.utils.file.FileUtils;
import com.vote.framework.config.ServerConfig;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.opencv.opencv_core.IplImage;
import org.bytedeco.opencv.opencv_core.Mat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    private static final String FILE_DELIMETER = ",";
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            //封面截图
            String coverName = System.currentTimeMillis() + ".jpg";
            //linux下
            String coverPath = filePath + "/covers/" + coverName;
            //win下
            //String coverPath = filePath + "\\covers\\" + coverName;
            String cover = serverConfig.getUrl() + "/profile/upload/covers/" + coverName;
         /*   //将当前用户上传的视频存储
            TbVote tbVote = new TbVote();
            //封面 .jpg 保存到用户
            tbVote.setvCover(cover);
            //视频地址
            tbVote.setvUrl(fileName);
            // 创建时间
            tbVote.setCreateTime(new Date());

            //获取用户的id 保存到用户表中
            LoginUser loginUser = tokenService.getLoginUser(request);
            tbVote.setvUid(Math.toIntExact(loginUser.getUserId()));
            //修改一下
            tbVoteService.updateVoteById(tbVote);*/

            AjaxResult ajax = AjaxResult.success();
            //截取视频的某一帧 作为封面
            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(url);
            grabber.start();
            Java2DFrameConverter converter = new Java2DFrameConverter();
            BufferedImage image = converter.convert(grabber.grabImage());
            ImageIO.write(image, "jpg", new File(coverPath));
            grabber.stop();
            ajax.put("url", url);
            ajax.put("cover", cover);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 视频FFmpeg处理
     *
     * @param videoFile
     * @return java.lang.String
     * @author WanShen
     * @date 2024/1/29 20:04
     */
    @PostMapping("/process-video")
    public String processVideo(@RequestParam("video") MultipartFile videoFile) throws IOException {
        String outputPath = "path/to/processed/video.mp4";

        // 保存上传的视频文件到服务器
        File uploadedVideo = new File("path/to/uploaded/video.mp4");
        videoFile.transferTo(uploadedVideo);

        // 使用FFmpeg处理视频
        String ffmpegCommand = String.format("ffmpeg -i %s -vf your_filter_here -c:a copy %s",
                uploadedVideo.getAbsolutePath(), outputPath);

        ProcessBuilder processBuilder = new ProcessBuilder(ffmpegCommand.split(" "));
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();
        try {
            process.waitFor();
            System.out.println("Video processing successful.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return outputPath;
    }

    @PostMapping("/checkVideo")
    @Anonymous
    public AjaxResult fenbianl(MultipartFile file) throws IOException {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath() + "/check";
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
//        视频处理 转成mp4
        try {
            //视频处理部分
            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(url);

            grabber.start();
            //获取宽和高
            int width = grabber.getImageWidth();
            int height = grabber.getImageHeight();


            // 获取视频旋转角度
            Java2DFrameConverter converter = new Java2DFrameConverter();
            Frame frame;
            // 获取视频的前几帧来判断方向
            for (int i = 0; i < 5; i++) {
                frame = grabber.grabImage();
                BufferedImage bufferedImage = converter.getBufferedImage(frame);

                if (bufferedImage != null) {
                    width = bufferedImage.getWidth();
                    height = bufferedImage.getHeight();
                    break;
                }
            }


            System.out.println("width:" + width + ",== height" + height);

            grabber.stop();
            if (width < height) {
                return AjaxResult.error("请录制横屏视频!");
            }


            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            file.getInputStream().close();
        }
        return AjaxResult.success();
    }

}
